import React, {useEffect} from 'react';
import { Form, Input, Select} from 'antd';

import {WrappedComponentProps} from "vendor/components/pro-hoc/withModal";

import { RespDataType, createMenu, updateMenu } from '../../../api';
import {EnumMenuType} from "../../constants";

interface DataAuthProps extends WrappedComponentProps{
    menuId?: number;
    optType: "add" | "edit";
    fetchList: () => void;
    editData?: RespDataType.MenuItem
}

const CreateOrEdit: React.FC<DataAuthProps> = ({ modalControl,optType, menuId, fetchList, editData }) => {
    const [ form ] = Form.useForm();

    useEffect(() => {
        modalControl.registerOk(handleSubmit);
    });

    const handleSubmit = () => {
        form.validateFields().then((values) => {
            const success = () => {
                fetchList();
                modalControl.close()
            }
            const error = () => modalControl.hideSaving();

            if(optType == "edit"){
                values.parentId = editData.parentId;
                updateMenu(menuId,values).then(success).catch(error)
            }else{
                values.parentId = menuId ? menuId : 0;
                createMenu(values).then(success).catch(error)
            }
        }).catch(() => modalControl.hideSaving())
    }

    return <Form
            form={form}
            initialValues={editData || {}}
            labelCol={{span: 6}}
            wrapperCol={{span: 16}}
        >
            <Form.Item
                label="菜单名称"
                name="menuName"
                rules={[{required: true, message: '菜单名称不能为空'}]}
            >
                <Input placeholder="请输入菜单名称"/>
            </Form.Item>

            <Form.Item
                label="权限标识"
                name="perms"
                rules={[{required: true, message: '权限标识不能为空'}]}
            >
                <Input placeholder="请输入权限标识"/>
            </Form.Item>


            <Form.Item
                label="菜单类型"
                name="menuType"
                rules={[{required: true, message: '菜单类型不能为空'}]}
            >
                <Select placeholder="请选择">
                    {EnumMenuType.map(({label, value}) => (
                        <Select.Option key={value} value={value}>{label}</Select.Option>
                    ))}
                </Select>
            </Form.Item>
        </Form>
}

export default CreateOrEdit

